package com.tan.user.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tan.common.domain.user.SysGroup;
import com.tan.common.dto.user.GroupCreateDTO;
import com.tan.common.dto.user.GroupUpdateDTO;
import com.tan.common.mapper.user.SysGroupMapper;
import com.tan.common.mapstruct.user.GroupConvert;
import com.tan.common.query.user.GroupQuery;
import com.tan.common.tools.ConvertTool;
import com.tan.common.tools.PageTool;
import com.tan.common.vo.user.GroupVO;
import com.tan.core.utils.ExceptionTool;
import com.tan.core.utils.StringUtils;
import com.tan.user.service.ISysGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Tan-Bowen
 * @description
 * @date 2025/2/20 14:23
 */
@Slf4j
@Service
public class SysGroupServiceImpl extends ServiceImpl<SysGroupMapper, SysGroup> implements ISysGroupService {

    @Override
    public IPage<GroupVO> groupPages(GroupQuery query) {
        LambdaQueryWrapper<SysGroup> wrapper = Wrappers.lambdaQuery(SysGroup.class);
        wrapper.eq(SysGroup::getDelFlag, false);
        wrapper.eq(query.getStatus() != null, SysGroup::getStatus, query.getStatus());
        wrapper.like(StringUtils.isNotBlank(query.getKeyword()), SysGroup::getName, query.getKeyword());
        IPage<SysGroup> pages = this.baseMapper.selectPage(new Page<>(query.getCurrent(), query.getSize()), wrapper);
        return PageTool.convert(pages, GroupConvert.class);
    }

    @Override
    public List<GroupVO> groupList() {
        LambdaQueryWrapper<SysGroup> wrapper = Wrappers.lambdaQuery(SysGroup.class);
        wrapper.eq(SysGroup::getDelFlag, false);
        wrapper.eq( SysGroup::getStatus, true);
        List<SysGroup> list = this.baseMapper.selectList(wrapper);
        return ConvertTool.toTarget(GroupConvert.class,list);
    }

    @Override
    public void createGroup(GroupCreateDTO groupCreateDTO) {
        SysGroup group = GroupConvert.INSTANCE.dtoDomain(groupCreateDTO);
        int count = this.baseMapper.insert(group);
        ExceptionTool.operateSqlError(count, "创建组失败");
    }

    @Override
    public void updateGroup(GroupUpdateDTO groupUpdateDTO) {
        SysGroup group = GroupConvert.INSTANCE.dtoDomain(groupUpdateDTO);
        int count = this.baseMapper.updateById(group);
        ExceptionTool.operateSqlError(count, "修改组失败");
    }

    @Override
    public void delGroup(Long groupId) {
        SysGroup group = this.baseMapper.selectById(groupId);
        ExceptionTool.isNullError(group, "此组不存在");
        group.setDelFlag(true);
        this.baseMapper.updateById(group);
    }


}
